﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;
using Chat.Framework;

namespace Chat.Server
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        //保存客户端通讯
        public static Dictionary<string, Socket> client = null;
        //声明监听套接字
        private Socket serverSocket = null;
        //监听标记
        private Boolean isListen = true;


        private void Startbtn_OnClick(object sender, RoutedEventArgs e)
        {
            if (serverSocket==null)
            {
                try
                {
                    client=new Dictionary<string, Socket>();
                    serverSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                    IPEndPoint endPoint=new IPEndPoint(IPAddress.Loopback, 8080);//端点
                    serverSocket.Bind(endPoint);
                    serverSocket.Listen(100);
                    Thread th=new Thread(StartListen);
                    th.IsBackground = true;
                    th.Start();
                    Msgtxt.Dispatcher.BeginInvoke(new Action(() => { Msgtxt.Text += "服务启动...\r\n"; }));
                }
                catch (SocketException ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        //线程函数，封装一个建立连接的通信套接字
        private void StartListen()
        {
            isListen = true;
            Socket clientSocket = default(Socket);
            while (isListen)
            {
                try
                {
                    clientSocket = serverSocket.Accept();
                }
                catch (SocketException e)
                {
                    File.AppendAllText($"{AppDomain.CurrentDomain.BaseDirectory}Exception.txt",e.Message);
                }

                Byte[] bytesFrom=new byte[4096];
                string dataFromClient = null;
                if (clientSocket != null && clientSocket.Connected)
                {
                    try
                    {
                        //获取客户端信息
                        int len = clientSocket.Receive(bytesFrom);
                        //存在数据
                        if (len > -1)
                        {
                            string tmp = Encoding.UTF8.GetString(bytesFrom);
                            try
                            {
                                //内容解密
                                dataFromClient = EncryptionAndDecryption.TripleDESDecrypting(tmp);
                            }
                            catch (Exception e)
                            {
                                
                            }

                            int sublen = dataFromClient.LastIndexOf("$");
                            if (sublen > -1)
                            {
                                //获取昵称
                                dataFromClient = dataFromClient.Substring(0, sublen);
                                //判断client 是否已经存在
                                if (!client.ContainsKey(dataFromClient))
                                {
                                    client.Add(dataFromClient, clientSocket);
                                    BroadCast.PushMessage($"{dataFromClient}Joined ", dataFromClient, false, client);
                                    HandleClient handleClient=new HandleClient();
                                    handleClient.StartClient(clientSocket, dataFromClient, client);
                                }
                                else
                                {
                                    clientSocket.Send(Encoding.UTF8.GetBytes(
                                        EncryptionAndDecryption.TripleDESEncrypting($"#{dataFromClient}#")));
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        File.AppendAllText($"{AppDomain.CurrentDomain.BaseDirectory}Exception.txt", e.Message);
                    }
                }
            }
        }

        private void Stopbtn_OnClick(object sender, RoutedEventArgs e)
        {
            if (serverSocket != null)
            {
                //关闭所有客户端
                foreach (Socket socket in client.Values)
                {
                    socket.Close();
                }
                //清空所有客户端
                client.Clear();
                //关闭服务器
                serverSocket.Close();
                serverSocket = null;
                isListen = false;
                Msgtxt.Text += "服务停止\r\n";
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            isListen = false;
            BroadCast.PushMessage("server has closed", "", false, client);
            client.Clear();
            serverSocket.Close();
            serverSocket = null;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                client=new Dictionary<string, Socket>();
                serverSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                IPEndPoint endPoint=new IPEndPoint(IPAddress.Loopback, 8080);
                serverSocket.Bind(endPoint);
                serverSocket.Listen(100);
                Thread th=new Thread(StartListen);
                th.IsBackground = true;
                th.Start();
                Msgtxt.Dispatcher.BeginInvoke(new Action(() => { Msgtxt.Text += "服务启动...\r\n"; }));
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
